﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml.Linq;

namespace LS.Api.Helper
{
    public static class RequestHelper
    {
        /// <summary>
        /// 获取客户端真实Ip
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP()
        {
            string result = string.Empty;
            try
            {
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (null == result || result == String.Empty)
                {
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }

                if (null == result || result == String.Empty)
                {
                    //result = HttpContext.Current.Request.UserHostAddress;
                    result = "127.0.0.1";
                }
            }
            catch (Exception)
            {

                result = "127.0.0.1";
            }

            return result == "::1" ? "127.0.0.1" : result;
        }


        /// <summary>
        /// 根据 User Agent 获取操作系统名称
        /// </summary>
        /// <param name="userAgent"></param>
        /// <returns></returns>
        public static string GetOSNameByUserAgent(string userAgent)
        {
            string osVersion = "未知";
            if (string.IsNullOrEmpty(userAgent))
            {
                return osVersion;
            }

            if (userAgent.Contains("NT 10.0"))
            {
                osVersion = "Windows 10";
            }
            else if (userAgent.Contains("NT 6.3"))
            {
                osVersion = "Windows 8.1";
            }
            else if (userAgent.Contains("NT 6.2"))
            {
                osVersion = "Windows 8";
            }
            else if (userAgent.Contains("NT 6.1"))
            {
                osVersion = "Windows 7";
            }
            else if (userAgent.Contains("NT 6.1"))
            {
                osVersion = "Windows 7";
            }
            else if (userAgent.Contains("NT 6.0"))
            {
                osVersion = "Windows Vista/Server 2008";
            }
            else if (userAgent.Contains("NT 5.2"))
            {
                if (userAgent.Contains("64"))
                    osVersion = "Windows XP";
                else
                    osVersion = "Windows Server 2003";
            }
            else if (userAgent.Contains("NT 5.1"))
            {
                osVersion = "Windows XP";
            }
            else if (userAgent.Contains("NT 5"))
            {
                osVersion = "Windows 2000";
            }
            else if (userAgent.Contains("NT 4"))
            {
                osVersion = "Windows NT4";
            }
            else if (userAgent.Contains("Me"))
            {
                osVersion = "Windows Me";
            }
            else if (userAgent.Contains("98"))
            {
                osVersion = "Windows 98";
            }
            else if (userAgent.Contains("95"))
            {
                osVersion = "Windows 95";
            }
            else if (userAgent.Contains("Mac"))
            {
                osVersion = "Mac";
            }
            else if (userAgent.Contains("Unix"))
            {
                osVersion = "UNIX";
            }
            else if (userAgent.Contains("Linux"))
            {
                osVersion = "Linux";
            }
            else if (userAgent.Contains("SunOS"))
            {
                osVersion = "SunOS";
            }
            else
            {
                osVersion = HttpContext.Current.Request.Browser.Platform;
            }
            return osVersion;
        }

        /// <summary>
        /// 获取当前系统的域名、IP
        /// </summary>
        /// <returns></returns>
        public static string GetCurrectDomain()
        {
            Uri currectUri = HttpContext.Current.Request.Url;
            StringBuilder hostName = new StringBuilder(currectUri.Scheme + "://");
            hostName.Append(currectUri.Host);
            if (currectUri.Port != 80)
            {
                hostName.Append(":" + currectUri.Port);
            }
            return hostName.ToString();
        }
        /// <summary>
        /// 转换类型
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="valueAsString"></param>
        /// <returns></returns>
        public static T? GetValueOrNull<T>(this string valueAsString) where T : struct
        {
            if (string.IsNullOrEmpty(valueAsString))
                return null;
            return (T)Convert.ChangeType(valueAsString, typeof(T));
        }
        public static T? GetQueryValueOrNull<T>(string key) where T : struct
        {
            var val = HttpContext.Current.Request[key];
            if (string.IsNullOrEmpty(val))
                return null;
            return (T)Convert.ChangeType(val, typeof(T));
        }
        public static T GetQueryValueOrNull<T>(string key, T defaultValue = default(T))
        {
            var val = HttpContext.Current.Request[key];
            if (string.IsNullOrEmpty(val))
                return defaultValue;
            return (T)Convert.ChangeType(val, typeof(T));
        }
        public static T GetValueOrDefault<T>(object val, T defaultValue = default(T))
        {
            if (val == null)
                return defaultValue;
            return (T)Convert.ChangeType(val, typeof(T));
        }

        /// <summary>
        /// 转换为string[]
        /// </summary>
        /// <param name="valueAsString"></param>
        /// <returns></returns>
        public static string[] GetStringArrayNoNull(this string valueAsString)
        {
            if (!string.IsNullOrEmpty(valueAsString))
            {
                valueAsString = valueAsString.Replace("|", ",").Replace("，", ",");
                return valueAsString.Split(',');
            }

            return new string[] { };
        }
        public static List<string> GetStringListNoNull(string strValues)
        {

            List<string> result = new List<string>();
            if (!string.IsNullOrEmpty(strValues))
            {
                strValues = strValues.Trim().Replace("|", ",").Replace("，", ",");
                return strValues.Split(',').ToList<string>();
            }

            return result;
        }
        /// <summary>
        /// 过滤危险字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string FilterParam(string str)
        {
            if (string.IsNullOrEmpty(str))
            {
                return String.Empty;
            }
            str = str.Replace("'", "");

            //删除与数据库相关的词
            str = Regex.Replace(str, "select", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "insert", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "delete from", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "count", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "drop table", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "truncate", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "asc", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "mid", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "char", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "xp_cmdshell", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "exec master", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "net localgroup administrators", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "and", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "net user", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "or", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "net", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "-", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "delete", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "drop", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "script", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "update", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "and", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "chr", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "master", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "truncate", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "declare", "", RegexOptions.IgnoreCase);
            str = Regex.Replace(str, "mid", "", RegexOptions.IgnoreCase);

            //编码字符
            str = Regex.Replace(str, @"\u0027", "", RegexOptions.IgnoreCase);

            return str;
        }

        /// <summary>
        /// 获取8位不重复的数字
        /// </summary>
        /// <returns></returns>
        public static string GetTakeCode()
        {
            byte[] randomBytes = new byte[4];
            RNGCryptoServiceProvider rngServiceProvider = new RNGCryptoServiceProvider();
            rngServiceProvider.GetBytes(randomBytes);
            Int32 result = BitConverter.ToInt32(randomBytes, 0);
            string takecode = result.ToString().Replace("-", "");
            if (takecode.Length > 8)
            {
                return takecode.Substring(0, 8);
            }
            else
            {
                return GetTakeCode();
            }
        }


        /// <summary>
        /// 逗号分割的字符转成sql的字符串
        /// </summary>
        /// <param name="strSplit"></param>
        /// <returns></returns>
        public static string GetStrSql(string strSplit)
        {
            if (string.IsNullOrEmpty(strSplit))
            {
                return string.Empty;
            }
            string[] aryval = strSplit.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            StringBuilder strsql = new StringBuilder();
            for (int i = 0; i < aryval.Length; i++)
            {
                strsql.Append("'" + aryval[i] + "',");
            }
            return System.Text.RegularExpressions.Regex.Replace(strsql.ToString(), ",$", "");
        }
        /// <summary>
        /// 去掉字符串末尾逗号字符
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string RemoveSuffixChar(string str)
        {
            return System.Text.RegularExpressions.Regex.Replace(str, ",$", "");
        }

        public static Dictionary<string, string> GetSystemConfig()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            try
            {

                string path = HttpContext.Current.Server.MapPath("/Configs/system.config");
                var xmlDocument = XDocument.Load(path);
                var appSettings = xmlDocument.Elements("appSettings").Elements();
                foreach (var item in appSettings)
                {

                    dic.Add(item.Attribute("key").Value, item.Attribute("value").Value);
                }


            }
            catch
            {

            }
            return dic;
        }

        public static string GetSystemConfigByKey(string key)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();

            try
            {

                string path = HttpContext.Current.Server.MapPath("/Configs/system.config");
                var xmlDocument = XDocument.Load(path);
                var appSettings = xmlDocument.Elements("appSettings").Elements();
                foreach (var item in appSettings)
                {
                    if (item.Attribute("key").Value == key)
                    {
                        return item.Attribute("value").Value;
                    }
                }
            }
            catch
            {

            }
            return string.Empty;
        }

        /// <summary>
        /// 格式化获取日期
        /// </summary>
        /// <param name="dateStr"></param>
        /// <returns></returns>
        public static List<string> GetDateForStr(string dateStr)
        {
            List<string> datels = new List<string>();
            var matchcoll = System.Text.RegularExpressions.Regex.Matches(dateStr, @"\d{4}-\d{2}-\d{2}");
            foreach (var item in matchcoll)
            {
                datels.Add(item.ToString());
            }
            return datels;
        }


        /// <summary>
        /// long ids 转sql ids 字符串
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public static string GetListToStr(List<long> ids)
        {
            return string.Join(",", ids);
        }



    }
}